
//
//  PhotoBrowserViewController.swift
//  weibo
//
//  Created by cmh on 15/9/14.
//  Copyright © 2015年 cmh. All rights reserved.
//

import UIKit
import SVProgressHUD

// cell 标识
private let XMYPhotoBrowserCellID = "XMYPhotoBrowserCellID"

class PhotoBrowserViewController: UIViewController {
    
    // MARK: - 设置属性
    var urls: [NSURL]
    
    var selectedIndexpath: NSIndexPath
    
    init(urls: [NSURL], indexPath: NSIndexPath){
        
        self.urls = urls
        selectedIndexpath = indexPath
        
        super.init(nibName: nil, bundle: nil)
    
    }
    
    @objc private func saveImage() {
        
        // 获取图片
        let indexpath = collectionView.indexPathsForVisibleItems().last!
        
        let cell = collectionView.cellForItemAtIndexPath(indexpath) as! PhotoBrowserCell
        
        // 保存图片
        guard let image = cell.iconView.image else {
            
            SVProgressHUD.showInfoWithStatus("没有图形")
            
            return
        }
        
         UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    // 图片保存成功的回调
    @objc private func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?) {
    
        let message = (error == nil) ? "保存成功" : "保存失败"
        
        SVProgressHUD.showInfoWithStatus(message)
        
    }
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func loadView() {
        
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20
        
        view = UIView(frame: rect)
        view.backgroundColor = UIColor.whiteColor()

        setupUI()
        
    }
    // 设置选中图片的时候滚动到当前页
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        collectionView.scrollToItemAtIndexPath(selectedIndexpath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        
    }
   
    // MARK: - 布局UI
    private func setupUI() {
        
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        view.addSubview(pageControl)
        
        collectionView.frame = view.bounds
        
        // 设置自动布局
        closeBtn.translatesAutoresizingMaskIntoConstraints = false
        saveBtn.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        
        let dictView = ["cb" : closeBtn, "sb" : saveBtn]
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[cb(==80)]-(>=8)-[sb(==80)]-8-|", options: [], metrics: nil, views: dictView))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[cb(35)]-8-|", options: [], metrics: nil, views: dictView))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[sb(35)]-8-|", options: [], metrics: nil, views: dictView))
        
        view.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -8))
        
        
        prepareCollectionView()
        preparePageControl()
        
        // 关闭和保存按钮的监听
        closeBtn.rac_signalForControlEvents(.TouchUpInside).subscribeNext { [weak self](btn) -> Void in
            self?.dismissViewControllerAnimated(true, completion: nil)
        }
        
        saveBtn.rac_signalForControlEvents(.TouchUpInside).subscribeNext { [weak self](btn) -> Void in
            self?.saveImage()
        }
        
        // 分页控件的点击时间
        pageControl.rac_signalForControlEvents(.ValueChanged).subscribeNext {[weak self] (pageControl) -> Void in
            
            // 获得当前点击的索引
            let index = NSIndexPath(forItem: pageControl.currentPage, inSection: 0)
            
            // 滚动
            self?.collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        }
        
        
    }
    
    // MARK: - 准备控件
    private func prepareCollectionView() {
        
        // 注册cell 
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: XMYPhotoBrowserCellID)
        
        // 设置数据源和代理
        collectionView.delegate = self
        collectionView.dataSource = self

        let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout
        
        layout?.itemSize = view.bounds.size
        
        layout?.minimumInteritemSpacing = 0
        layout?.minimumLineSpacing = 0
        
        layout?.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView.pagingEnabled = true
    }
    
    private func preparePageControl() {
        
        pageControl.numberOfPages = urls.count
        
        pageControl.currentPage = selectedIndexpath.item

        // 单页隐藏
        pageControl.hidesForSinglePage = true
        
        pageControl.pageIndicatorTintColor = UIColor.whiteColor()

        pageControl.currentPageIndicatorTintColor = UIColor.redColor()
        
    }
    
    
    // MARK: - 懒加载控件
    private lazy var closeBtn: UIButton = UIButton(title: "关闭", fontSize: 15)
    
    private lazy var saveBtn: UIButton = UIButton(title: "保存", fontSize: 15)
    
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
    
    private lazy var pageControl: UIPageControl = UIPageControl()

    
}

extension PhotoBrowserViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return urls.count
        
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(XMYPhotoBrowserCellID, forIndexPath: indexPath) as! PhotoBrowserCell
        
        cell.url = urls[indexPath.item]
        
        return cell
        
    }
    
    // 滚动完成的时候调用
    func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
        pageControl.currentPage = collectionView.indexPathsForVisibleItems().last?.item ?? 0
        
    }
}
